package com.aggeek.springbootlearning;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * author:liuao
 * description:
 * Date: create on 15:24 2017/12/11
 * modify by:
 */
public class ApacheHttpClient {
    /**
     * 流程创建httpclient，构建httpget，httpclient.execute(httpget)返回respone
     * 通过response获取实体（HttpEntity），实体utils获取字符串
     * 记住关闭response
     * 关闭httpclient
     * @param url
     * @return
     */
    public static JSONObject get(String url){
        CloseableHttpClient httpclient = null;
        httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        JSONObject jsonObject=null;
        try {
            CloseableHttpResponse execute = httpclient.execute(httpGet);
            HttpEntity entity = execute.getEntity();

            if (entity!=null){
                String s = EntityUtils.toString(entity);
                jsonObject = JSONObject.parseObject(s);
            }
            execute.close();

        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            if(httpclient!=null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return  jsonObject;
    }

    /**
     * 创建httpclient，httppost，参数队列List<BasicNameValuePair>,
     * 使用urlencodedformentity格式化参数，编码，httppost设置参数实体
     * excute获得response接下里流程一样
     * @param url
     * @param params
     * @return
     */
    public static JSONObject post(String url, Map<String,String> params){
        JSONObject jsonObject = new JSONObject() ;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建httppost
        HttpPost httppost = new HttpPost(url);
        // 创建参数队列
        List formparams = new ArrayList();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        Iterator<Map.Entry<String, String>> iterator = entries.iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String> next = iterator.next();
            String key = next.getKey();
            String vale = next.getValue();

            formparams.add(new BasicNameValuePair(key, vale));
        }
        UrlEncodedFormEntity uefEntity;

        try {
            uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
            httppost.setEntity(uefEntity);
            CloseableHttpResponse execute = httpclient.execute(httppost);
            try {
                HttpEntity entity = execute.getEntity();
                if(entity!=null){
                    String s = EntityUtils.toString(entity);
                    jsonObject = JSONObject.parseObject(s);
                }
            }finally {
                execute.close();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    return  jsonObject;
    }
}
